home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: Michael Smith <msmith@mpx.com.au>
- Newsgroups: comp.lang.c,comp.lang.c.moderated
- Subject: Re: Leading and Trailing Blanks
- Date: 5 Jan 1996 09:53:01 -0600
- Organization: Emmenjay Consulting
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4cjhgt$f87@solutions.solon.com>
- References: <4chh1b$685@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
- X-Mailer: Mozilla 2.0b3 (Win16; I)
-
-
- Casey Claiborne wrote:
- >
- > Hello -
- > I am wondering if anyone out there has a program (or knows of one)
- > that allows one to strip leading and trailing blanks from a string.
- > ex:
- >
- > char test[20];
- > strcpy(test," TESTING ");
- > printf("%s", test);
- >
- > will produce an output like
- > TESTING
- >
- > that has blanks at the beginning of "TESTING". I would like to
- > have the following result
- >
- > TESTING
-
- The following code has not been tested, so probably contains typos.
- It should serve to illustrate the algorithm.
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- #define TRUE 1
- #define FALSE 0
-
- char *dupstr( str ); /* defined below */
-
- /**************************************************************/
- /* trimstr - Remove leading and trailing blanks from a string */
- /* Return TRUE (OK) or FALSE (Error) */
- /**************************************************************/
- int trimstr( char *str )
- {
- {
- char *buff, *start, *end;
- int *len;
-
-
- /* MAKE A COPY OF THE STRING */
- buff = dupstr( str );
- if (buff==NULL) return( FALSE );
-
- /* FIND FIRST NON-BLANK CHAR */
- start = buff;
- while (start==' ') start++;
-
- /* TRIM TRAILING BLANKS */
- len = strlen( start );
- end = start+len-1;
- while (end>=start && *end==' ') *(end--)='\0';
-
-
- /* COPY BACK TO ORIGINAL STRING */
- strcpy( str, start );
-
-
- /* FREE TEMP BUFFER */
- free( buff );
-
- return( TRUE );
- }
- }
-
-
- /*******************************************************************/
- /* dupstr - Emulate non-ANSI strdup() function: duplicate a string */
- /*******************************************************************/
- char *dupstr( char *str )
- {
- {
- char *newstr = malloc( strlen(str)+1 );
-
-
- if (newstr) strcpy( newstr, str );
- return( newstr );
- }
- }
-
-
- --
- #####################################################################
- Michael Smith msmith@mpx.com.au
- Emmenjay Consulting
- Sofware Development System Administration/Management
- Applications Support PC Installation/Maintenance
- Training Technical Writing
- Windows/Unix General Consulting/Troubleshooting
-
- PO Box 909 Ph 018 240 704
- Kensington 2033
- AUSTRALIA
- #####################################################################
-